<template>
  <view class="service-detail-container">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 服务详情内容 -->
    <view v-else-if="service" class="detail-content">
      <!-- 图片轮播 -->
      <view class="image-section" v-if="service.images && service.images.length > 0">
        <swiper 
          class="service-swiper" 
          :indicator-dots="service.images.length > 1" 
          :autoplay="false"
          indicator-color="rgba(255,255,255,0.5)"
          indicator-active-color="#22c55e"
        >
          <swiper-item v-for="(image, index) in service.images" :key="index">
            <image :src="image" class="service-image" mode="aspectFill" />
          </swiper-item>
        </swiper>
      </view>
      
      <!-- 服务信息卡片 -->
      <view class="info-card">
        <view class="service-header">
          <text class="service-title">{{ service.title }}</text>
          <view class="service-tags">
            <text class="tag verified" v-if="service.audit_status === 'APPROVED'">✓ 认证</text>
            <text class="tag deposit" v-if="service.deposit_required > 0">保证金</text>
            <text class="tag category">{{ service.category?.name || '服务' }}</text>
          </view>
        </view>
        
        <view class="service-description" v-if="service.basic_services">
          <text class="desc-title">基本服务</text>
          <text class="desc-content">{{ service.basic_services }}</text>
        </view>
        
        <view class="service-description" v-if="service.extended_services">
          <text class="desc-title">擅长服务</text>
          <text class="desc-content">{{ service.extended_services }}</text>
        </view>
        
        <view class="service-description" v-if="service.after_sale_service">
          <text class="desc-title">售后保证</text>
          <text class="desc-content">{{ service.after_sale_service }}</text>
        </view>
        
        <!-- 联系信息 -->
        <view class="contact-section">
          <view class="contact-item" v-if="service.user?.nickname">
            <text class="contact-label">联系人：</text>
            <text class="contact-value">{{ service.user.nickname }}</text>
          </view>

          <!-- 手机号显示逻辑 -->
          <view class="contact-item" v-if="service.user?.phone || service.user?.id">
            <text class="contact-label">联系电话：</text>

            <!-- 未查看状态: 显示加密手机号 + 查看按钮 -->
            <view v-if="!isContactVisible" class="contact-phone-wrapper">
              <text class="contact-value phone encrypted">138****5678</text>
              <button
                class="view-contact-btn"
                @click="viewContact"
                :disabled="viewContactLoading"
                size="mini"
                type="default"
              >
                {{ viewContactLoading ? '加载中...' : '查看' }}
              </button>
            </view>

            <!-- 已查看状态: 显示真实手机号 + 拨打按钮 -->
            <view v-else class="contact-phone-wrapper">
              <text class="contact-value phone">{{ realContactInfo?.phone_number || service.user.phone }}</text>
              <button
                class="call-btn"
                @click="makePhoneCall"
                size="mini"
                type="primary"
              >
                拨打
              </button>
            </view>
          </view>
        </view>
        
        <!-- 地理位置信息 -->
        <view class="location-section">
          <view class="location-item">
            <text class="location-label">服务地区：</text>
            <text class="location-value">{{ service.province }} {{ service.city }}</text>
          </view>
        </view>
        
        <!-- 时间信息 -->
        <view class="time-section">
          <view class="time-item">
            <text class="time-label">发布时间：</text>
            <text class="time-value">{{ formatTime(service.created_at) }}</text>
          </view>
          <view class="time-item" v-if="service.updated_at !== service.created_at">
            <text class="time-label">更新时间：</text>
            <text class="time-value">{{ formatTime(service.updated_at) }}</text>
          </view>
        </view>
      </view>
      
      <!-- 互动操作区域 -->
      <view class="interaction-section">
        <view class="interaction-buttons">
          <view class="interaction-item" @click="toggleLike">
            <view class="interaction-icon-wrapper" :class="{ 'liked': service.is_liked }">
              <text class="interaction-icon">♥</text>
            </view>
            <text class="interaction-count">{{ service.like_count || 0 }}</text>
            <text class="interaction-label">点赞</text>
          </view>
          
          <view class="interaction-item" @click="focusCommentInput">
            <view class="interaction-icon-wrapper">
              <text class="interaction-icon">💬</text>
            </view>
            <text class="interaction-count">{{ service.comment_count || 0 }}</text>
            <text class="interaction-label">评论</text>
          </view>
        </view>
      </view>
      
      <!-- 评论列表 -->
      <view class="comments-section">
        <view class="section-title">评论 ({{ service?.comment_count || 0 }})</view>
        
        <scroll-view 
          class="comment-list" 
          scroll-y="true"
          @scrolltolower="loadMoreComments"
        >
          <view 
            v-for="comment in commentList" 
            :key="comment.id"
            class="comment-item"
          >
            <image 
              :src="comment.users.avatar_url || '/static/default-avatar.png'" 
              class="comment-avatar"
            ></image>
            <view class="comment-content">
              <view class="comment-user">{{ comment.users.nickname || '用户' }}</view>
              <view class="comment-text">{{ comment.content }}</view>
              <view class="comment-time">{{ formatTime(comment.created_at) }}</view>
            </view>
          </view>
          
          <!-- 加载状态 -->
          <view class="loading" v-if="commentLoading">
            <text>加载中...</text>
          </view>
          <view class="no-more" v-if="commentNoMore && commentList.length > 0">
            <text>没有更多评论了</text>
          </view>
          <view class="empty" v-if="!commentLoading && commentList.length === 0">
            <text>暂无评论，来发表第一条评论吧~</text>
          </view>
        </scroll-view>
      </view>

      <!-- 评论输入框 -->
      <view class="comment-input-section">
        <input 
          v-model="commentContent"
          placeholder="发表评论..."
          class="comment-input"
          maxlength="500"
          @focus="onCommentFocus"
          @blur="onCommentBlur"
        />
        <view 
          class="send-btn"
          :class="{ 'active': commentContent.trim() }"
          @click="sendComment"
        >
          发送
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="action-buttons">
        <button class="action-btn secondary" @click="goBack">
          返回
        </button>
        <button class="action-btn primary contact-quote-btn" @click="startPrivateChat" :disabled="isStartingChat">
          <text class="btn-icon">💬</text>
          {{ isStartingChat ? '发起中...' : '沟通报价' }}
        </button>
      </view>
    </view>
    
    <!-- 错误状态 -->
    <view v-else class="error-container">
      <text class="error-text">服务详情加载失败</text>
      <button class="retry-btn" @click="loadServiceDetail">重新加载</button>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { localServiceAPI, chatAPI, contactViewAPI } from '@/utils/api.js'
import CreditChecker from '@/utils/creditChecker.js'

// 响应式数据
const service = ref(null)
const loading = ref(true)
const serviceId = ref('')
const isStartingChat = ref(false)
const commentList = ref([])
const commentContent = ref('')
const commentLoading = ref(false)
const commentPage = ref(1)
const commentPageSize = ref(20)
const commentNoMore = ref(false)
const isContactVisible = ref(false)       // 联系方式是否已查看
const viewContactLoading = ref(false)     // 查看联系方式加载状态
const realContactInfo = ref(null)         // 真实的联系方式数据

// 页面加载时获取参数
onLoad((options) => {
  serviceId.value = options.id || ''
  
  if (serviceId.value) {
    loadServiceDetail()
    loadComments(true)
  } else {
    loading.value = false
    uni.showToast({
      title: '参数错误',
      icon: 'error'
    })
  }
})

// 方法定义
/**
 * 加载服务详情
 */
const loadServiceDetail = async () => {
  try {
    loading.value = true
    const result = await localServiceAPI.getServiceDetail(serviceId.value)
    
    if (result.success) {
      service.value = result.data
      console.log('服务详情加载成功:', {
        id: service.value.id,
        like_count: service.value.like_count,
        comment_count: service.value.comment_count,
        is_liked: service.value.is_liked
      })
    } else {
      uni.showToast({
        title: result.message || '加载失败',
        icon: 'error'
      })
    }
  } catch (error) {
    console.error('加载服务详情失败:', error)
    uni.showToast({
      title: '网络错误',
      icon: 'error'
    })
  } finally {
    loading.value = false
  }
}

/**
 * 查看联系方式(需要消耗额度)
 */
const viewContact = async () => {
  if (!service.value?.user?.id) {
    uni.showToast({
      title: '用户信息不完整',
      icon: 'none'
    })
    return
  }

  try {
    // 1. 先检查额度
    const hasCredit = await CreditChecker.checkContactViewCredit({
      fromPage: `/pages/local-services/detail?id=${serviceId.value}`
    })

    if (!hasCredit) {
      return // 额度不足时,CreditChecker会自动弹窗引导购买
    }

    // 2. 调用现有的contact-view接口获取真实联系方式
    viewContactLoading.value = true
    const response = await contactViewAPI.getUserContact(service.value.user.id)

    if (response.success) {
      // 3. 保存真实联系方式并显示
      realContactInfo.value = response.data
      isContactVisible.value = true

      // 4. 如果使用了购买的额度,本地扣减
      if (response.data.used_credits) {
        CreditChecker.reduceLocalCredit(CreditChecker.CREDIT_TYPES.CONTACT_VIEW, 1)
      }

      uni.showToast({
        title: '获取成功',
        icon: 'success'
      })
    } else {
      uni.showToast({
        title: response.message || '获取失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('查看联系方式失败:', error)
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
  } finally {
    viewContactLoading.value = false
  }
}

/**
 * 拨打电话(修改为使用realContactInfo)
 */
const makePhoneCall = () => {
  const phoneNumber = realContactInfo.value?.phone_number || service.value?.user?.phone
  if (phoneNumber) {
    uni.makePhoneCall({
      phoneNumber: phoneNumber,
      fail: (err) => {
        console.error('拨打电话失败:', err)
        uni.showToast({
          title: '拨打电话失败',
          icon: 'error'
        })
      }
    })
  }
}

/**
 * 发起私聊
 */
const startPrivateChat = async () => {
  if (!service.value?.user?.id) {
    uni.showToast({
      title: '服务商信息不完整',
      icon: 'none'
    })
    return
  }
  
  try {
    isStartingChat.value = true
    // 发起私聊
    const response = await chatAPI.startPrivateChat(service.value.user.id)
    if (response.success) {
      // 跳转到私聊页面
      uni.navigateTo({
        url: `/pages/chat/private?userId=${service.value.user.id}&nickname=${encodeURIComponent(service.value.user.nickname || '用户')}`
      })
    } else {
      uni.showToast({
        title: response.message || '发起私聊失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('发起私聊错误:', error)
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
  } finally {
    isStartingChat.value = false
  }
}

/**
 * 点赞/取消点赞
 */
const toggleLike = async () => {
  if (!service.value) return
  
  try {
    const response = await localServiceAPI.toggleLike(serviceId.value)
    if (response.success) {
      // 使用后端返回的准确数据更新本地状态
      service.value.is_liked = response.data.liked
      service.value.like_count = response.data.like_count || 0
    }
  } catch (error) {
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    })
  }
}

/**
 * 加载评论列表
 */
const loadComments = async (refresh = false) => {
  if (commentLoading.value) return
  
  commentLoading.value = true
  
  try {
    const page = refresh ? 1 : commentPage.value
    const response = await localServiceAPI.getComments(serviceId.value, page, commentPageSize.value)
    
    if (response.success) {
      const { comments, pagination } = response.data
      
      if (refresh) {
        commentList.value = comments
        commentPage.value = 1
        commentNoMore.value = false
      } else {
        commentList.value = [...commentList.value, ...comments]
      }
      
      commentPage.value = pagination.current_page + 1
      commentNoMore.value = pagination.current_page >= pagination.total_pages
    }
  } catch (error) {
    uni.showToast({
      title: '评论加载失败',
      icon: 'none'
    })
  } finally {
    commentLoading.value = false
  }
}

/**
 * 加载更多评论
 */
const loadMoreComments = () => {
  if (!commentNoMore.value && !commentLoading.value) {
    loadComments()
  }
}

/**
 * 发送评论
 */
const sendComment = async () => {
  if (!commentContent.value.trim()) return
  
  try {
    const response = await localServiceAPI.createComment(serviceId.value, commentContent.value.trim())
    
    if (response.success) {
      // 添加评论到列表顶部
      commentList.value.unshift(response.data.comment)
      // 更新评论数量
      if (service.value) {
        service.value.comment_count += 1
      }
      // 清空输入框
      commentContent.value = ''
      
      uni.showToast({
        title: '评论成功',
        icon: 'success'
      })
    }
  } catch (error) {
    uni.showToast({
      title: '评论失败',
      icon: 'none'
    })
  }
}

/**
 * 聚焦评论输入框
 */
const focusCommentInput = () => {
  // 这里可以滚动到底部并聚焦输入框
}

/**
 * 评论输入框聚焦
 */
const onCommentFocus = () => {
  // 可以在这里做一些UI调整
}

/**
 * 评论输入框失焦
 */
const onCommentBlur = () => {
  // 可以在这里做一些UI调整
}

/**
 * 格式化时间
 */
const formatTime = (timeStr) => {
  if (!timeStr) return '刚刚'
  
  const time = new Date(timeStr)
  if (isNaN(time.getTime())) {
    return '刚刚'
  }
  
  const now = new Date()
  const diff = now - time
  
  if (diff < 60 * 1000) {
    return '刚刚'
  } else if (diff < 60 * 60 * 1000) {
    return Math.floor(diff / (60 * 1000)) + '分钟前'
  } else if (diff < 24 * 60 * 60 * 1000) {
    return Math.floor(diff / (60 * 60 * 1000)) + '小时前'
  } else if (diff < 7 * 24 * 60 * 60 * 1000) {
    return Math.floor(diff / (24 * 60 * 60 * 1000)) + '天前'
  } else {
    return time.toLocaleDateString()
  }
}

/**
 * 返回上一页
 */
const goBack = () => {
  uni.navigateBack({
    delta: 1
  })
}
</script>

<style scoped>
.service-detail-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 180rpx;
}

.loading-container, .error-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 20rpx;
}

.loading-text, .error-text {
  font-size: 28rpx;
  color: #666;
}

.retry-btn {
  padding: 20rpx 40rpx;
  background-color: #22c55e;
  color: white;
  border: none;
  border-radius: 8rpx;
  font-size: 26rpx;
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

/* 图片轮播样式 */
.image-section {
  margin: 0;
}

.service-swiper {
  height: 400rpx;
  width: 100%;
}

.service-image {
  width: 100%;
  height: 100%;
}

/* 信息卡片样式 */
.info-card {
  background-color: white;
  margin: 0 20rpx;
  border-radius: 12rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.service-header {
  margin-bottom: 20rpx;
}

.service-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
  margin-bottom: 15rpx;
  display: block;
}

.service-tags {
  display: flex;
  gap: 10rpx;
  flex-wrap: wrap;
}

.tag {
  font-size: 20rpx;
  padding: 6rpx 12rpx;
  border-radius: 6rpx;
  color: white;
}

.tag.verified {
  background-color: #22c55e;
}

.tag.deposit {
  background-color: #f59e0b;
}

.tag.category {
  background-color: #6366f1;
}

/* 描述样式 */
.service-description {
  margin-bottom: 25rpx;
}

.desc-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 10rpx;
  display: block;
}

.desc-content {
  font-size: 26rpx;
  color: #666;
  line-height: 1.6;
}

/* 联系信息样式 */
.contact-section {
  margin-bottom: 25rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #f1f3f4;
}

.contact-item {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
  gap: 10rpx;
}

.contact-item:last-child {
  margin-bottom: 0;
}

.contact-label {
  font-size: 26rpx;
  color: #666;
  min-width: 160rpx;
}

.contact-value {
  font-size: 26rpx;
  color: #333;
  flex: 1;
}

.contact-value.phone {
  color: #22c55e;
  font-weight: 600;
}

.contact-phone-wrapper {
  display: flex;
  align-items: center;
  gap: 10rpx;
  flex: 1;
}

.contact-value.phone.encrypted {
  color: #999;
  font-style: italic;
}

.view-contact-btn {
  font-size: 22rpx !important;
  padding: 8rpx 20rpx !important;
  height: auto !important;
  line-height: 1.2 !important;
  background-color: #22c55e !important;
  color: white !important;
  border: none !important;
}

.view-contact-btn[disabled] {
  background-color: #ccc !important;
  color: #999 !important;
}

.call-btn {
  font-size: 22rpx !important;
  padding: 8rpx 16rpx !important;
  height: auto !important;
  line-height: 1.2 !important;
  background-color: #22c55e !important;
}

/* 地理位置样式 */
.location-section {
  margin-bottom: 25rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #f1f3f4;
}

.location-item {
  display: flex;
  margin-bottom: 10rpx;
}

.location-item:last-child {
  margin-bottom: 0;
}

.location-label {
  font-size: 26rpx;
  color: #666;
  min-width: 160rpx;
}

.location-value {
  font-size: 26rpx;
  color: #333;
  flex: 1;
}

/* 时间信息样式 */
.time-section {
  padding-top: 20rpx;
  border-top: 1rpx solid #f1f3f4;
}

.time-item {
  display: flex;
  margin-bottom: 10rpx;
}

.time-item:last-child {
  margin-bottom: 0;
}

.time-label {
  font-size: 24rpx;
  color: #999;
  min-width: 160rpx;
}

.time-value {
  font-size: 24rpx;
  color: #999;
  flex: 1;
}

/* 操作按钮样式 */
.action-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  padding: 20rpx;
  border-top: 1rpx solid #e5e5e5;
  display: flex;
  gap: 20rpx;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.action-btn {
  flex: 1;
  height: 88rpx;
  border-radius: 44rpx;
  font-size: 30rpx;
  font-weight: 600;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-btn.primary {
  background-color: #22c55e;
  color: white;
}

.contact-quote-btn {
  background: linear-gradient(135deg, #ff6b6b, #ff8e8e) !important;
  box-shadow: 0 4rpx 20rpx rgba(255, 107, 107, 0.4) !important;
  transform: scale(1.02);
  animation: pulse-glow 2s ease-in-out infinite;
  border: 2rpx solid #ff4757 !important;
}

.contact-quote-btn .btn-icon {
  font-size: 32rpx;
  margin-right: 8rpx;
  animation: bounce 1s ease-in-out infinite;
}

.contact-quote-btn:active {
  background: linear-gradient(135deg, #ff5252, #ff7979) !important;
  transform: scale(0.98);
}

.action-btn.primary:active {
  background-color: #16a34a;
}

.action-btn.primary:disabled {
  background-color: #cccccc;
  color: #999999;
}

.action-btn.secondary {
  background-color: #6c757d;
  color: white;
}

.action-btn.secondary:active {
  background-color: #5a6268;
}

/* 互动操作区域样式 */
.interaction-section {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.interaction-buttons {
  display: flex;
  padding: 30rpx;
  gap: 60rpx;
  justify-content: flex-start;
}

.interaction-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
  cursor: pointer;
  transition: all 0.2s ease;
}

.interaction-item:active {
  transform: scale(0.95);
}

.interaction-icon-wrapper {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background-color: #f8f9fa;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  border: 2rpx solid transparent;
}

.interaction-icon-wrapper.liked {
  background-color: #fee2e2;
  border-color: #ef4444;
}

.interaction-icon {
  font-size: 32rpx;
  color: #666;
  transition: all 0.3s ease;
}

.interaction-icon-wrapper.liked .interaction-icon {
  color: #ef4444;
  animation: heartBeat 0.6s ease;
}

.interaction-count {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  min-width: 40rpx;
  text-align: center;
}

.interaction-label {
  font-size: 24rpx;
  color: #666;
}

/* 点赞动画 */
@keyframes heartBeat {
  0% { transform: scale(1); }
  14% { transform: scale(1.3); }
  28% { transform: scale(1); }
  42% { transform: scale(1.3); }
  70% { transform: scale(1); }
}

/* 沟通报价按钮动画 */
@keyframes pulse-glow {
  0% {
    box-shadow: 0 4rpx 20rpx rgba(255, 107, 107, 0.4);
  }
  50% {
    box-shadow: 0 6rpx 30rpx rgba(255, 107, 107, 0.6);
  }
  100% {
    box-shadow: 0 4rpx 20rpx rgba(255, 107, 107, 0.4);
  }
}

@keyframes bounce {
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-4rpx);
  }
  60% {
    transform: translateY(-2rpx);
  }
}

/* 评论区域样式 */
.comments-section {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 12rpx;
}

.section-title {
  padding: 30rpx;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  border-bottom: 1rpx solid #f0f0f0;
}

.comment-list {
  max-height: 600rpx;
}

.comment-item {
  display: flex;
  padding: 30rpx;
  border-bottom: 1rpx solid #f8f8f8;
}

.comment-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 30rpx;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.comment-content {
  flex: 1;
}

.comment-user {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.comment-text {
  font-size: 30rpx;
  color: #333;
  line-height: 1.5;
  margin-bottom: 8rpx;
}

.comment-time {
  font-size: 24rpx;
  color: #999;
}

/* 评论输入框样式 */
.comment-input-section {
  position: fixed;
  bottom: 120rpx;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #eee;
  display: flex;
  align-items: center;
}

.comment-input {
  flex: 1;
  padding: 16rpx 24rpx;
  background-color: #f5f5f5;
  border-radius: 40rpx;
  font-size: 28rpx;
  margin-right: 20rpx;
}

.send-btn {
  padding: 16rpx 32rpx;
  background-color: #ddd;
  color: #999;
  border-radius: 40rpx;
  font-size: 28rpx;
}

.send-btn.active {
  background-color: #22c55e;
  color: #fff;
}

/* 加载状态样式 */
.loading, .no-more, .empty {
  text-align: center;
  padding: 40rpx;
  color: #999;
  font-size: 28rpx;
}
</style>